using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 测试AI助手高级检索工具功能
    /// </summary>
    public class TestAdvancedTools
    {
        private readonly ILogger<TestAdvancedTools> _logger;
        private readonly AgentToolService _agentToolService;

        public TestAdvancedTools()
        {
            // 创建日志记录器
            var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            _logger = loggerFactory.CreateLogger<TestAdvancedTools>();

            // 创建AgentToolService实例
            var agentLogger = loggerFactory.CreateLogger<AgentToolService>();
            _agentToolService = new AgentToolService(agentLogger);
        }

        /// <summary>
        /// 运行所有测试
        /// </summary>
        public async Task RunAllTestsAsync()
        {
            Console.WriteLine("🚀 开始测试AI助手高级检索工具功能...\n");

            try
            {
                // 设置测试项目
                var testProject = new Project
                {
                    Id = 999,
                    Name = "测试项目",
                    RootPath = Path.Combine(Directory.GetCurrentDirectory(), "Projects", "Project_3"),
                    Type = "Novel"
                };
                _agentToolService.SetCurrentProject(testProject);

                await TestBasicFileOperations();
                await TestScanProjectStructure();
                await TestGetFileSummary();
                await TestAnalyzeFileRelationships();
                await TestDeepContentSearch();
                await TestGetProjectOverview();

                Console.WriteLine("✅ 所有测试完成！");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"❌ 测试过程中发生错误: {ex.Message}");
                _logger.LogError(ex, "测试失败");
            }
        }

        /// <summary>
        /// 测试基础文件操作
        /// </summary>
        private async Task TestBasicFileOperations()
        {
            Console.WriteLine("📁 测试基础文件操作...");
            
            // 测试列出文件
            var result = await _agentToolService.ExecuteToolAsync("list_files", "");
            Console.WriteLine(result);
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 测试项目结构扫描
        /// </summary>
        private async Task TestScanProjectStructure()
        {
            Console.WriteLine("📁 测试项目结构扫描...");
            var result = await _agentToolService.ExecuteToolAsync("scan_project_structure", "");
            Console.WriteLine(result);
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 测试文件摘要生成
        /// </summary>
        private async Task TestGetFileSummary()
        {
            Console.WriteLine("📄 测试文件摘要生成...");
            
            // 查找第一个文本文件进行测试
            var projectPath = Path.Combine(Directory.GetCurrentDirectory(), "Projects", "Project_3");
            if (Directory.Exists(projectPath))
            {
                var files = Directory.GetFiles(projectPath, "*.md", SearchOption.AllDirectories);
                if (files.Length == 0)
                {
                    files = Directory.GetFiles(projectPath, "*.txt", SearchOption.AllDirectories);
                }
                
                if (files.Length > 0)
                {
                    var testFile = Path.GetRelativePath(Directory.GetCurrentDirectory(), files[0]);
                    var result = await _agentToolService.ExecuteToolAsync("get_file_summary", testFile);
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine("未找到测试文件");
                }
            }
            else
            {
                Console.WriteLine("测试项目路径不存在");
            }
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 测试文件关系分析
        /// </summary>
        private async Task TestAnalyzeFileRelationships()
        {
            Console.WriteLine("🔗 测试文件关系分析...");
            var result = await _agentToolService.ExecuteToolAsync("analyze_file_relationships", "");
            Console.WriteLine(result);
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 测试深度内容搜索
        /// </summary>
        private async Task TestDeepContentSearch()
        {
            Console.WriteLine("🔍 测试深度内容搜索...");
            var result = await _agentToolService.ExecuteToolAsync("deep_content_search", "时间");
            Console.WriteLine(result);
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 测试项目概览
        /// </summary>
        private async Task TestGetProjectOverview()
        {
            Console.WriteLine("📊 测试项目概览...");
            var result = await _agentToolService.ExecuteToolAsync("get_project_overview", "");
            Console.WriteLine(result);
            Console.WriteLine(new string('-', 50));
        }

        /// <summary>
        /// 主入口点
        /// </summary>
        public static async Task Main(string[] args)
        {
            var tester = new TestAdvancedTools();
            await tester.RunAllTestsAsync();
            
            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }
    }
}
